
#import <Foundation/Foundation.h>
#import "TCVideoRecordViewController.h"
#import <TXLiteAVSDK_Professional/TXUGCRecord.h>
#import <TXLiteAVSDK_Professional/TXLiveRecordTypeDef.h>
#import <TXLiteAVSDK_Professional/TXVideoEditer.h>
#import "TCVideoPublishController.h"
#import "V8HorizontalPickerView.h"
#import <AVFoundation/AVFoundation.h>
#import "TCVideoEditViewController.h"

/********************  美狐开始  ******************/
#import "MHMeiyanMenusView.h"
#import <MHBeautySDK/MHBeautyManager.h>
#import <MHBeautySDK/MHSDK.h>
#import "MHBeautyParams.h"
/********************  美狐结束  ******************/
#import "AlbumVideoVC.h"
#import <MobileCoreServices/MobileCoreServices.h>

#import "SpeedView.h"
#import "VideoRecordProcessView.h"
#import "WuyouTangMusicView.h"

#import <TXVideoEditerTypeDef.h>
#import "YBProgressObj.h"
#import <TZImagePickerController/TZImagePickerController.h>
#import "YBPicTransitionVC.h"
#import "RKHorPickerView.h"
#import "YBVipVC.h"
#import "TXBaseBeautyView.h"

#define BUTTON_RECORD_SIZE          65
#define BUTTON_CONTROL_SIZE         40

@interface TCVideoRecordViewController()<TXUGCRecordListener,UIImagePickerControllerDelegate,UINavigationControllerDelegate,TXVideoCustomProcessDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,TXVideoJoinerListener,TZImagePickerControllerDelegate,RKPickerViewDelegate,MHMeiyanMenusViewDelegate> {
    
    UIImage *videobackImage;
    NSString *exportPath;
    BOOL _cameraFront;
    BOOL _lampOpened;
    BOOL _cameraPreviewing;
    BOOL _videoRecording;
    UIView *_videoRecordView;
   
    UIButton *_btnCamera;
    UIButton *_btnLamp;
    UIButton *_btnBeauty;
    UIButton *_musicBtn;
    
    UILabel *_recordTimeLabel;
    float _currentRecordTime;
    BOOL _appForeground;
    BOOL _isPaused;
    
    UIButton *_btnLocalVideo;//获取本地视频
    UIButton *_btnPicSel;
   
    BOOL _musicPlayed;
    
    NSArray *_stop_imgs;
    NSMutableArray *_stop_record_array;
    
    SpeedView *_speedV;
    RKHorPickerView *_tPickView;
    VideoRecordProcessView *_progressView;
    UIButton *_btnDelete;

    BOOL isTXfiter;
    
    //->合拍
    TXVideoEditer *_editor;
    TXUGCRecord   *_recorder;
    TXVideoJoiner *_joiner;
    TXVideoInfo    *_videoInfo;
    NSString       *_resultPath;
    UIView *_samePlayView;
    UIView *_sameRecordView;
    BOOL   _isBackDelete;
    BOOL _barHidden;
    //<-
    BOOL isLoadWebSprout;
    UIButton * _btnClose;
    BOOL _needScale;
}
@property(nonatomic,strong) UIButton *btnStartRecord;
@property(nonatomic,strong)UIButton *btnDone;

/********************  美狐开始  ******************/
@property(nonatomic,strong)UIButton *mhShadowBtn;
@property(nonatomic,strong)MHMeiyanMenusView *menusView;
@property(nonatomic,strong)MHBeautyManager *beautyManager;
/********************  美狐结束  ******************/
@end

@implementation TCVideoRecordViewController

-(instancetype)init {
    self = [super init];
    if (self) {
        _musicPlayed = NO;
        _cameraFront = YES;
        _lampOpened = NO;
        _cameraPreviewing = NO;
        _videoRecording = NO;
        _currentRecordTime = 0.0;

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAppDidEnterBackGround:) name:UIApplicationDidEnterBackgroundNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAppWillEnterForeground:) name:UIApplicationWillEnterForegroundNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAudioSessionEvent:) name:AVAudioSessionInterruptionNotification object:nil];
        
        _appForeground = YES;
    }
    return self;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
     NSLog(@"rk20200118===录制====内存内存内存=======");
}

- (void)dealloc {
//    [self destroyRecordSource];
    NSLog(@"record-dealloc");
}

-(void)destroyRecordSource {
    if (_videoRecording) {
        [self stopVideoRecord];
    }
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    NSLog(@"rk=======111111");
    if (self.beautyManager) {
//        [self.beautyManager destroy];
        self.beautyManager = nil;
        NSLog(@"rk=======22222");
    }
    [[TXUGCRecord shareInstance].partsManager deleteAllParts];
    [self releaseEditor];
    NSLog(@"rk20200118===录制===dealloc");
}

-(void)releaseEditor {
    if (_editor) {
        [_editor stopPlay];
        _editor = nil;
    }
    if (_joiner) {
        _joiner.joinerDelegate = nil;
        _joiner = nil;
    }
}
-(void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    self.navigationController.interactivePopGestureRecognizer.delegate =nil;
    
    _barHidden = YES;
    self.naviView.hidden = YES;
    [self initUI];
    
    _stop_imgs = @[@"录制1",@"录制2",@"录制3",@"录制4",@"录制5",@"录制6",@"录制7",@"录制6",@"录制5",@"录制4",@"录制3",@"录制2",@"录制1"];
    
    _stop_record_array = [NSMutableArray array];
    for (int i=0; i<_stop_imgs.count; i++) {
        UIImage *img = [UIImage imageNamed:_stop_imgs[i]];
        [_stop_record_array addObject:img];
    }
    
    [[YBProgressObj progressManeger]setUpViewCancelHidden:YES andComplete:nil];
    [YBProgressObj progressManeger].generationHidden = YES;
    
    NSInteger deviceType = [PublicObj getDeviceType];
    //iPhone6s
    if (deviceType >= 8){
        _needScale = NO;
    }else{
        _needScale = YES;
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
   
    [self.navigationController setNavigationBarHidden:YES];
    [UIApplication sharedApplication].statusBarHidden = YES;
    isLoadWebSprout = NO;
    [self startCameraPreview];
    [self showBtnWhenEnd:NO];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

    [UIApplication sharedApplication].statusBarHidden = NO;
    _barHidden = NO;
//    [self stopCameraPreview:YES];
}

#pragma mark ---- Common UI ----
-(void)initUI {
    
    CGFloat startTop = 40+statusbarHeight;
    CGFloat btnWith = 66;
    CGFloat btnHeight = 56;
    UIFont *btnFont = SYS_Font(12);
    
    if (_recordType == RecordType_Chorus) {
        _sameRecordView = [[UIView alloc]initWithFrame:CGRectMake(0, statusbarHeight+130, _window_width/2, _window_width/2*16/9)];
        [self.view addSubview:_sameRecordView];
        _samePlayView = [[UIView alloc]initWithFrame:CGRectMake(_window_width/2, _sameRecordView.top, _sameRecordView.width, _sameRecordView.height)];
        [self.view addSubview:_samePlayView];
        
        // 视频拼接
        _joiner = [[TXVideoJoiner alloc] initWithPreview:nil];
        _joiner.joinerDelegate = self;
    }else {
        _videoRecordView = [[UIView alloc] initWithFrame:self.view.frame];
        [self.view addSubview:_videoRecordView];
    }
    
    UIImageView* mask_top = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, BUTTON_CONTROL_SIZE)];
    [mask_top setImage:[UIImage imageNamed:@"video_record_mask_top"]];
    [self.view addSubview:mask_top];
    
    UIImageView* mask_buttom = [[UIImageView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - 100, self.view.frame.size.width, 100)];
    [mask_buttom setImage:[UIImage imageNamed:@"video_record_mask_buttom"]];
    [self.view addSubview:mask_buttom];
    
    //底层遮罩
    UIView *botShadowView = [[UIView alloc]init];
    botShadowView.backgroundColor = UIColor.clearColor;
    [self.view addSubview:botShadowView];
    
    CGFloat record_reduce = 90;
    CGFloat time_reduce = 0;
    if (iPhoneX) {
        record_reduce = 100;
        time_reduce = 15;
    }
    
    //开始录制
    _btnStartRecord = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 80, 80)];
    _btnStartRecord.center = CGPointMake(_window_width / 2, _window_height - record_reduce);
    [_btnStartRecord setImage:[UIImage imageNamed:getImagename(@"startrecord")] forState:UIControlStateNormal];
    [_btnStartRecord setImage:[UIImage imageNamed:@"startrecord_press"] forState:UIControlStateSelected];
    [_btnStartRecord addTarget:self action:@selector(onBtnRecordStartClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_btnStartRecord];
    _btnStartRecord.userInteractionEnabled = NO;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //确保预览成功按钮可点击,避免界面刚预览便疯狂点击,
        _btnStartRecord.userInteractionEnabled = YES;
    });
    
    //时间选择(60、15s)
    _tPickView = [[RKHorPickerView alloc]initWithFrame:CGRectMake(0, _btnStartRecord.bottom, _window_width, 30)];
    _tPickView.backgroundColor = UIColor.clearColor;
    _tPickView.delegate = self;
    NSString *sm_str = [NSString stringWithFormat:YZMsg(@"拍%.f秒"),normal_max];
    NSString *mx_str = [NSString stringWithFormat:YZMsg(@"拍%.f秒"),vip_max];
    if ([lagType isEqual:EN]) {
        sm_str = [NSString stringWithFormat:@"%.fs",normal_max];
        mx_str = [NSString stringWithFormat:@"%.fs",vip_max];
    }
    _tPickView.dataArray = @[sm_str,mx_str];
    [_tPickView scrollToIndex:0];
    MAX_RECORD_TIME = normal_max;
    MIN_RECORD_TIME = normal_min;
    [self.view addSubview:_tPickView];
    _tPickView.hidden = (_recordType == RecordType_Chorus || [[YBPower getVipSwitch]isEqual:@"0"])?YES:NO;
    
    //速度控制
    _speedV = [[SpeedView alloc]initWithFrame:CGRectMake(_window_width*0.2, _btnStartRecord.top-45, _window_width*0.6, 30)];
    _speedV.hidden = (_recordType == RecordType_Chorus)?YES:NO;
    _speedV.speedEvent = ^(int type) {
        if (type == 0) {
            [[TXUGCRecord shareInstance] setRecordSpeed:VIDEO_RECORD_SPEED_SLOWEST];
        }else if (type == 1){
            [[TXUGCRecord shareInstance] setRecordSpeed:VIDEO_RECORD_SPEED_SLOW];
        }else if (type == 2){
            [[TXUGCRecord shareInstance] setRecordSpeed:VIDEO_RECORD_SPEED_NOMAL];
        }else if (type == 3){
            [[TXUGCRecord shareInstance] setRecordSpeed:VIDEO_RECORD_SPEED_FAST];
        }else if (type == 4){
            [[TXUGCRecord shareInstance] setRecordSpeed:VIDEO_RECORD_SPEED_FASTEST];
        }
    };
    [self.view addSubview:_speedV];
    
    //进度
    _progressView = [[VideoRecordProcessView alloc] initWithFrame:CGRectMake(0,_window_height-2, _window_width, 20)];
    _progressView.alpha = 1;
    [_progressView updateMinTime:MIN_RECORD_TIME andMaxTime:MAX_RECORD_TIME];
    [self.view addSubview:_progressView];
    
    //时间
    _recordTimeLabel = [[UILabel alloc]init];
    _recordTimeLabel.frame = CGRectMake(0, 0, 100, 100);
    [_recordTimeLabel setText:@"00:00"];
    _recordTimeLabel.font = [UIFont systemFontOfSize:10];
    _recordTimeLabel.textColor = [UIColor whiteColor];
    _recordTimeLabel.textAlignment = NSTextAlignmentLeft;
    [_recordTimeLabel sizeToFit];
    _recordTimeLabel.center = CGPointMake(CGRectGetMaxX(_progressView.frame) - _recordTimeLabel.frame.size.width / 2-time_reduce, _progressView.frame.origin.y - _recordTimeLabel.frame.size.height);
    [self.view addSubview:_recordTimeLabel];
    
    //返回
    _btnClose = [[UIButton alloc] init];
    [_btnClose setImage:[UIImage imageNamed:@"pub_back"] forState:UIControlStateNormal];
    [_btnClose addTarget:self action:@selector(onBtnCloseClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_btnClose];
    [_btnClose mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@20);
        make.left.equalTo(self.view);
        make.width.equalTo(@(btnWith));
        make.height.equalTo(@(btnHeight));
    }];
    
    //摄像头
    _btnCamera = [UIButton buttonWithType:UIButtonTypeCustom];
    [_btnCamera setTitle:YZMsg(@"翻转") forState:0];
    [_btnCamera setImage:[UIImage imageNamed:@"镜头"] forState:UIControlStateNormal];
    _btnCamera.titleLabel.font = btnFont;
    [_btnCamera addTarget:self action:@selector(onBtnCameraClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_btnCamera];
    [_btnCamera mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@(startTop));
        make.right.equalTo(self.view).offset(-5);
        make.width.equalTo(@(btnWith));
        make.height.equalTo(@(btnHeight));
    }];
    
    //闪光灯
    _btnLamp = [UIButton buttonWithType:UIButtonTypeCustom];
    [_btnLamp setTitle:YZMsg(@"闪光灯") forState:0];
    [_btnLamp setImage:[UIImage imageNamed:@"闪光关"] forState:UIControlStateNormal];
    _btnLamp.titleLabel.font = btnFont;
    [_btnLamp addTarget:self action:@selector(onBtnLampClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_btnLamp];
    [_btnLamp mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_btnCamera.mas_bottom).offset(8);
        make.right.equalTo(self.view).offset(-5);
        make.width.equalTo(@(btnWith));
        make.height.equalTo(@(btnHeight));
    }];
    
    //美颜
    _btnBeauty = [UIButton buttonWithType:UIButtonTypeCustom];
    [_btnBeauty setTitle:YZMsg(@"美颜") forState:0];
    [_btnBeauty setImage:[UIImage imageNamed:@"美颜"] forState:UIControlStateNormal];
    _btnBeauty.titleLabel.font = btnFont;
    [_btnBeauty addTarget:self action:@selector(onBtnBeautyClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_btnBeauty];
    [_btnBeauty mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_btnLamp.mas_bottom).offset(8);
        make.right.equalTo(self.view).offset(-5);
        make.width.equalTo(@(btnWith));
        make.height.equalTo(@(btnHeight));
    }];
    
    //音乐
    _musicBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_musicBtn setTitle:YZMsg(@"音乐") forState:0];
    [_musicBtn setImage:[UIImage imageNamed:@"音乐"] forState:UIControlStateNormal];
    _musicBtn.titleLabel.font = btnFont;
    [_musicBtn addTarget:self action:@selector(onBtnMusicClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_musicBtn];
    [_musicBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_btnBeauty.mas_bottom).offset(8);
        make.right.equalTo(self.view).offset(-5);
        make.width.equalTo(@(btnWith));
        make.height.equalTo(@(btnHeight));
    }];
    if (_recordType == RecordType_Chorus || _isTakeSame) {
        //_musicBtn.alpha = 0.5;
        //_musicBtn.enabled = NO;
        _musicBtn.hidden = YES;
    }
    
    //图片转场
    _btnPicSel = [[UIButton alloc] init];
    [_btnPicSel setImage:[UIImage imageNamed:@"图片转场"] forState:UIControlStateNormal];
    [_btnPicSel setImage:[UIImage imageNamed:@"图片转场"] forState:UIControlStateSelected];
    [_btnPicSel setTitle:YZMsg(@"图片转场") forState:UIControlStateNormal];
    _btnPicSel.titleLabel.font = btnFont;
    [_btnPicSel addTarget:self action:@selector(onBtnPicSelClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_btnPicSel];
    _btnPicSel.hidden = (_recordType == RecordType_Chorus)?YES:NO;;
    [_btnPicSel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_btnStartRecord);
        make.width.equalTo(@(btnWith));
        make.height.equalTo(@(btnHeight));
        make.centerX.equalTo(self.view.mas_centerX).multipliedBy(0.45);
    }];
    
    //获取本地视频
    _btnLocalVideo = [[UIButton alloc] init];
    [_btnLocalVideo setImage:[UIImage imageNamed:@"上传"] forState:UIControlStateNormal];
    [_btnLocalVideo setImage:[UIImage imageNamed:@"上传"] forState:UIControlStateSelected];
    [_btnLocalVideo setTitle:YZMsg(@"上传") forState:UIControlStateNormal];
    _btnLocalVideo.titleLabel.font = btnFont;
    [_btnLocalVideo addTarget:self action:@selector(onBtnLocalVideoClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_btnLocalVideo];
    _btnLocalVideo.hidden = (_recordType == RecordType_Chorus)?YES:NO;
    [_btnLocalVideo mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_btnStartRecord);
        make.width.equalTo(@(btnWith));
        make.height.equalTo(@(btnHeight));
        make.centerX.equalTo(self.view.mas_centerX).multipliedBy(1.55);
    }];
    
    //删除
    _btnDelete = [UIButton buttonWithType:UIButtonTypeCustom];
    [_btnDelete setImage:[UIImage imageNamed:@"录制删除"] forState:UIControlStateNormal];
    [_btnDelete addTarget:self action:@selector(onBtnDeleteClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_btnDelete];
    _btnDelete.hidden = YES;
    [_btnDelete mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_btnStartRecord);
        make.width.height.equalTo(@(BUTTON_CONTROL_SIZE));
        make.centerX.equalTo(self.view.mas_centerX).multipliedBy(1.4);
    }];
    
    //下一步
    _btnDone = [UIButton buttonWithType:UIButtonTypeCustom];
    [_btnDone setTitleColor:[UIColor whiteColor] forState:0];
    [_btnDone setImage:[UIImage imageNamed:@"下一步"] forState:0];
    _btnDone.titleLabel.font = SYS_Font(14);
    [_btnDone addTarget:self action:@selector(onBtnDoneClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_btnDone];
    _btnDone.hidden = YES;
    [_btnDone mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_btnStartRecord);
        make.width.height.equalTo(@(BUTTON_CONTROL_SIZE));
        make.centerX.equalTo(self.view.mas_centerX).multipliedBy(1.75);
    }];
    
    [botShadowView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.width.centerX.equalTo(self.view);
        make.top.equalTo(_speedV.mas_top);
    }];
    
    //布置上图下文字
    [self.view layoutIfNeeded];
    _btnCamera = [PublicObj setUpImgDownText:_btnCamera];
    _btnLamp = [PublicObj setUpImgDownText:_btnLamp];
    _btnBeauty = [PublicObj setUpImgDownText:_btnBeauty];
    _musicBtn = [PublicObj setUpImgDownText:_musicBtn];
    _btnLocalVideo = [PublicObj setUpImgDownText:_btnLocalVideo];
    _btnPicSel = [PublicObj setUpImgDownText:_btnPicSel];

}
#pragma mark - 选择时间开始
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row{
    NSLog(@"***selectRow: %ld",row);
    if ( [[YBPower getCanTakeLongVideo] isEqual:@"0"] && row == 1) {
        //[MBProgressHUD showPop:@"您暂时还未获取拍摄长视频权限"];
        [self vipLimiteAlert:[NSString stringWithFormat:@"%@%.f%@",YZMsg(@"您不是会员用户,无法录制"),vip_max,YZMsg(@"秒长视频")]];
        [_tPickView scrollToIndex:0];
        return;
    }
    MAX_RECORD_TIME = ((row == 1) ? vip_max:normal_max);
    [self resetUGCConfig:YES];
}
-(void)vipLimiteAlert:(NSString *)msg {
    NSDictionary *contentDic = @{@"title":@"",
                                  @"msg":msg,
                                  @"left":YZMsg(@"取消"),
                                  @"right":YZMsg(@"开通会员")};
    [YBAlertView showAlertView:contentDic complete:^(int eventType) {
         if (eventType == 1) {
             [UIApplication sharedApplication].statusBarHidden = NO;
             dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                 YBVipVC *vipVC = [[YBVipVC alloc]init];
                 [[YBBaseAppDelegate sharedAppDelegate]pushViewController:vipVC animated:YES];
             });
         }
     }];
}

- (void)pickerViewBeginScroll{
    NSLog(@"pickerViewBeginScroll");
}
#pragma mark - 选择时间结束
//本地视频
-(void)onBtnLocalVideoClicked{
    
    [self selLocOrPicTransition];
    _btnLocalVideo.userInteractionEnabled = NO;
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        _btnLocalVideo.userInteractionEnabled = YES;
//    });
//    [UIApplication sharedApplication].statusBarHidden = NO;
    
    //方式三 tz去选择视频
    TZImagePickerController *imagePC = [[TZImagePickerController alloc]initWithMaxImagesCount:1 delegate:self];
    imagePC.preferredLanguage = [lagType isEqual:ZH_CN] ? @"zh-Hans":@"en";
    imagePC.iconThemeColor = Pink_Cor;
    imagePC.naviBgColor = CellRow_Cor;
    imagePC.oKButtonTitleColorNormal = Pink_Cor;
    imagePC.oKButtonTitleColorDisabled = Pink_Cor_Dis;
    imagePC.allowTakePicture = NO;
    imagePC.allowTakeVideo = NO;
    imagePC.allowPickingVideo = YES;
    imagePC.allowPickingImage = NO;
    imagePC.allowCrop = NO;
    imagePC.modalPresentationStyle = 0;
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    [self presentViewController:imagePC animated:YES completion:^{
        _btnLocalVideo.userInteractionEnabled = YES;
    }];
//    });
    
}
-(void)selLocOrPicTransition {
    //rk-1107
    if (_videoRecording)    {
        [self stopCameraPreview:YES];
        [self stopVideoRecord];
        [self refreshRecordTime:0];
        [[TXUGCRecord shareInstance].partsManager deleteAllParts];
    }
    
    /** 当用户从音乐界面选择了音乐的时候，这时又点击了从本地上传就把选择的音乐置空 */
    if (!_isTakeSame) {
        _haveBGM = NO;
        _musicPath=@"";
    }
}

#pragma mark - 预览
-(void)resetUGCConfig:(BOOL)isReset {
    if (isReset) {
        [[TXUGCRecord shareInstance] stopCameraPreview];
    }
    TXUGCCustomConfig * param = [[TXUGCCustomConfig alloc] init];
    //分辨率
    param.videoResolution =  VIDEO_RESOLUTION_1080_1920;///VIDEO_RESOLUTION_720_1280;
    param.videoFPS = 20;
    param.videoBitratePIN = 9000;
    param.GOP = 3;
    param.enableAEC = YES;
    param.minDuration = MIN_RECORD_TIME;
    param.maxDuration = MAX_RECORD_TIME;
    param.frontCamera = YES;
    [[TXUGCRecord shareInstance] startCameraCustom:param preview:_videoRecordView];
    [_progressView updateMinTime:MIN_RECORD_TIME andMaxTime:MAX_RECORD_TIME];
}
-(void)startCameraPreview {
    if (_cameraPreviewing == NO) {
        //自定义设置
        //合拍
        if (_recordType == RecordType_Chorus) {
            [[TXUGCRecord shareInstance]setMute:YES];
            [self isChorusEvent];
        }else {
            [self resetUGCConfig:NO];
        }
        [_progressView updateMinTime:MIN_RECORD_TIME andMaxTime:MAX_RECORD_TIME];
        //rk-1-16
        [TXUGCRecord shareInstance].recordDelegate = self;
        [TXUGCRecord shareInstance].videoProcessDelegate = self;
        [[[TXUGCRecord shareInstance] getBeautyManager] setBeautyStyle:0];
        [[[TXUGCRecord shareInstance] getBeautyManager] setRuddyLevel:0];
        
        if ([PublicObj isBaseBeauty]) {
            isTXfiter = YES;
            [[[TXUGCRecord shareInstance] getBeautyManager] setBeautyLevel:[TXBaseBeautyView getBaseBeautyValue]];
            [[[TXUGCRecord shareInstance] getBeautyManager] setWhitenessLevel:[TXBaseBeautyView getBaseWhiteValue]];
            [[TXUGCRecord shareInstance] setVideoRenderMode:VIDEO_RENDER_MODE_FULL_FILL_SCREEN];

        }else{
            isTXfiter = NO;
            [[[TXUGCRecord shareInstance] getBeautyManager] setBeautyLevel:0];
            [[[TXUGCRecord shareInstance] getBeautyManager] setWhitenessLevel:0];
            [[TXUGCRecord shareInstance] setVideoRenderMode:VIDEO_RENDER_MODE_FULL_FILL_SCREEN];
            [[TXUGCRecord shareInstance]switchCamera:YES];
            [[MHSDK shareInstance] initWithAppID:[common getTISDKAppid] key:[common getTISDKKey]];
//            [[MHSDK shareInstance]initWithAppID:@"33893d3ce4ad50e38efa067755386b24" key:@"061e4b4758d2f8a3afd0a095f543f091"];

        }
        [[[TXUGCRecord shareInstance] getBeautyManager] setEyeScaleLevel:0];
        //[[TXUGCRecord shareInstance] switchCamera:_cameraFront];
        _cameraPreviewing = YES;
    }
}
#pragma mark - 合拍参数
-(void)isChorusEvent {
    
     _videoInfo = [TXVideoInfoReader getVideoInfo:_mp4Path];
     TXAudioSampleRate audioSampleRate = AUDIO_SAMPLERATE_48000;
     if (_videoInfo.audioSampleRate == 8000) {
         audioSampleRate = AUDIO_SAMPLERATE_8000;
     }else if (_videoInfo.audioSampleRate == 16000){
         audioSampleRate = AUDIO_SAMPLERATE_16000;
     }else if (_videoInfo.audioSampleRate == 32000){
         audioSampleRate = AUDIO_SAMPLERATE_32000;
     }else if (_videoInfo.audioSampleRate == 44100){
         audioSampleRate = AUDIO_SAMPLERATE_44100;
     }else if (_videoInfo.audioSampleRate == 48000){
         audioSampleRate = AUDIO_SAMPLERATE_48000;
     }
     // 设置录像的保存路径
     _resultPath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"result.mp4"];
    // 播放器初始化
     TXPreviewParam *param = [[TXPreviewParam alloc] init];
     param.videoView = _samePlayView;
     param.renderMode = RENDER_MODE_FILL_EDGE;
     _editor = [[TXVideoEditer alloc] initWithPreview:param];
     [_editor setVideoPath:_mp4Path];
     // 录像参数初始化
     TXUGCCustomConfig *recordConfig = [[TXUGCCustomConfig alloc] init];
    recordConfig.videoResolution = VIDEO_RESOLUTION_1080_1920;//VIDEO_RESOLUTION_720_1280;
     //这里保证录制视频的帧率和合唱视频的帧率一致，否则可能出现音画不同步的现象
     //注意：这里获取的合唱视频的帧率是平均帧率，有可能为小数，做一下四舍五入操作
     recordConfig.videoFPS = (int)(_videoInfo.fps + 0.5);
     //这里保证录制视频的音频采样率和合唱视频的音频采样率一致，否则可能出现音画不同步的现象
     recordConfig.audioSampleRate = audioSampleRate;
    recordConfig.videoBitratePIN = 9600;//2400;
    MAX_RECORD_TIME = _videoInfo.duration;
    //rk_20200118 tx6.9解决合拍问题
    MIN_RECORD_TIME = normal_min;//_videoInfo.duration;
     recordConfig.maxDuration = MAX_RECORD_TIME;
     recordConfig.minDuration = MIN_RECORD_TIME;
    recordConfig.frontCamera = YES;
     // 启动相机预览
     [[TXUGCRecord shareInstance] startCameraCustom:recordConfig preview:_sameRecordView];
    
}

-(void)stopCameraPreview:(BOOL)stop {
    if (_cameraPreviewing == YES)    {
        if (stop) {
            [[TXUGCRecord shareInstance] stopCameraPreview];
        }
        _cameraPreviewing = NO;
        //rk-1-16
        [[[TXUGCRecord shareInstance]getBeautyManager] setFilter:nil];//[UIImage new]
        [TXUGCRecord shareInstance].recordDelegate = nil;
        [TXUGCRecord shareInstance].videoProcessDelegate = nil;
    }

}
#pragma  mark - 点击事件
-(void)onBtnRecordStartClicked {
    
    if (!_videoRecording) {
        [self startVideoRecord];
    } else {
        if (_isPaused) {
            [[TXUGCRecord shareInstance] resumeRecord];
            [_editor resumePlay];
            if (_musicPath.length>0) {
                [self tcPlayMusic];
            }
            [self hideBtnWhenRecord];
            _btnStartRecord.imageView.animationImages = _stop_record_array;
            _btnStartRecord.imageView.animationDuration = _stop_record_array.count*0.1;
            _btnStartRecord.imageView.animationRepeatCount = 0;
            [_btnStartRecord.imageView startAnimating];
            _isPaused = NO;
        }else {
            [self showBtnWhenEnd:NO];
            [[TXUGCRecord shareInstance] pauseRecord];
            [_editor pausePlay];
            //音乐暂停
            if (_musicPath.length>0) {
                [self tcPause];
            }
            [_btnStartRecord.imageView stopAnimating];
            [_btnStartRecord setImage:[UIImage imageNamed:getImagename(@"startrecord")] forState:UIControlStateNormal];
            [_btnStartRecord setImage:[UIImage imageNamed:@"startrecord_press"] forState:UIControlStateSelected];
            _isPaused = YES;
            [_progressView pause];
            _btnDelete.hidden = NO;
            
        }
    }
}

-(void)startVideoRecord {
    
    [self refreshRecordTime:0.0];
    [self startCameraPreview];
    
    int result =[[TXUGCRecord shareInstance] startRecord];
    if (0 != result) {
        [MBProgressHUD showPop:[NSString stringWithFormat:@"%@:%d",YZMsg(@"启动失败"),result]];
    }else{
        [_editor startPlayFromTime:0 toTime:_videoInfo.duration];
        [self hideBtnWhenRecord];
        
        _btnStartRecord.imageView.animationImages = _stop_record_array;
        _btnStartRecord.imageView.animationDuration = _stop_record_array.count*0.1;
        _btnStartRecord.imageView.animationRepeatCount = 0;
        [_btnStartRecord.imageView startAnimating];
        
        //先开启录制再播放音乐
        //选择音乐了这里就播放
        if (_musicPath.length>0) {
            [self tcPlayMusic];
        }
        
        _videoRecording = YES;
        _isPaused = NO;
    }
   
}

-(void)stopVideoRecord {
    [self showBtnWhenEnd:YES];
    
    [_progressView deleteAllPart];
    
    [[TXUGCRecord shareInstance] stopRecord];
    if (_musicPath.length>0) {
        [self tcStopMuic];
    }
    [_btnStartRecord.imageView stopAnimating];

    [_btnStartRecord setImage:[UIImage imageNamed:getImagename(@"startrecord")] forState:UIControlStateNormal];
    [_btnStartRecord setImage:[UIImage imageNamed:@"startrecord_press"] forState:UIControlStateSelected];
    
    _isPaused = NO;
    _videoRecording = NO;
    
}
#pragma mark - 删除
-(void)onBtnDeleteClicked {
    YBWeakSelf;
    NSDictionary *contentDic = @{@"title":YZMsg(@"提示"),@"msg":YZMsg(@"确定删除上一段视频?"),@"left":YZMsg(@"取消"),@"right":YZMsg(@"确定")};
    [YBAlertView showAlertView:contentDic complete:^(int eventType) {
        if (eventType == 1) {
            [weakSelf sureDelLast];
        }
    }];
    
}

-(void)sureDelLast {
    TXUGCPartsManager *partsManager = [TXUGCRecord shareInstance].partsManager;
    // 删除最后一段视频
    [partsManager deleteLastPart];
    _isBackDelete = YES;
    //获取当前所有视频片段的总时长
    _currentRecordTime = [partsManager getDuration];
    
    [self refreshRecordTime:_currentRecordTime];
    [_progressView prepareDeletePart];
    [_progressView comfirmDeletePart];
    if (_currentRecordTime < MIN_RECORD_TIME) {
        _btnDone.hidden = YES;
    }
    if (_currentRecordTime <= 0) {
        _btnLocalVideo.hidden = NO;
        _btnPicSel.hidden = NO;
        _tPickView.hidden = [[YBPower getVipSwitch] isEqual:@"0"] ? YES:NO;
        _speedV.hidden = (_recordType == RecordType_Chorus)?YES:NO;
        if (_recordType == RecordType_Chorus) {
            _btnLocalVideo.hidden = YES;
            _btnPicSel.hidden = YES;
            _tPickView.hidden = YES;
        }
        _btnDelete.hidden = YES;
        _btnDone.hidden = YES;
    }
}

- (void)onBtnDoneClicked {
    
    _btnDone.enabled = NO;
    _btnDone.alpha = 0.5;
    YBWeakSelf;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        weakSelf.btnDone.enabled = YES;
        weakSelf.btnDone.alpha = 1;
    });
    
    if (!_videoRecording)
        return;
    if (_recordType == RecordType_Chorus) {
        [_editor stopPlay];
    }
    [self stopVideoRecord];
    if (_musicPath.length>0) {
        [[TXUGCRecord shareInstance] stopBGM];
        _musicPlayed = NO;
    }
}
-(void)onBtnCloseClicked {
    if (!_isPaused && _videoRecording) {
        [self onBtnRecordStartClicked];
    }
    YBWeakSelf;
    RKActionSheet *sheet = [[RKActionSheet alloc]initWithTitle:@""];
    if (_currentRecordTime > 0) {
        [sheet addActionWithType:RKSheet_Default andTitle:YZMsg(@"重新拍摄") complete:^{
            [weakSelf resetTake];
        }];
    }
    [sheet addActionWithType:RKSheet_Default andTitle:YZMsg(@"退出") complete:^{
        [weakSelf doExitTake];
    }];
    [sheet addActionWithType:RKSheet_Cancle andTitle:YZMsg(@"取消") complete:^{
    }];
    [sheet showSheet];
   
}
-(void)doExitTake {
    [self stopCameraPreview:YES];
    [self stopVideoRecord];
    [self removeSameEventOfFile];
    [self destroyRecordSource];
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)resetTake {
    TXUGCPartsManager *partsManager = [TXUGCRecord shareInstance].partsManager;
    [partsManager deleteAllParts];
    [_progressView deleteAllPart];
    [self refreshRecordTime:0];
    if (_currentRecordTime <= 0) {
        _btnLocalVideo.hidden = NO;
        _btnPicSel.hidden = NO;
        _tPickView.hidden = [[YBPower getVipSwitch] isEqual:@"0"] ? YES:NO;
        if (_recordType == RecordType_Chorus) {
            _btnLocalVideo.hidden = YES;
            _btnPicSel.hidden = YES;
            _tPickView.hidden = YES;
        }
        _btnDelete.hidden = YES;
        _btnDone.hidden = YES;
    }
    if (_musicPath) {
        [self tcStopMuic];
    }
}

-(void)onBtnCameraClicked {
    if (_lampOpened) {
        _lampOpened = NO;
         [_btnLamp setImage:[UIImage imageNamed:@"闪光关"] forState:UIControlStateNormal];
    }
    _cameraFront = !_cameraFront;
    if (_cameraFront)    {
        [_btnCamera setImage:[UIImage imageNamed:@"镜头"] forState:UIControlStateNormal];
    }else{
        [_btnCamera setImage:[UIImage imageNamed:@"镜头"] forState:UIControlStateNormal];
    }
    [[TXUGCRecord shareInstance] switchCamera:_cameraFront];
}

-(void)onBtnLampClicked {
    if (_cameraFront) {
        [MBProgressHUD showPop:YZMsg(@"只有后置摄像头才能开启闪光灯")];
        return;
    }
    _lampOpened = !_lampOpened;
    BOOL result = [[TXUGCRecord shareInstance] toggleTorch:_lampOpened];
    if (result == NO)    {
        _lampOpened = !_lampOpened;
        [MBProgressHUD showPop:YZMsg(@"闪光灯启动失败")];
    }
    if (_lampOpened) {
        [_btnLamp setImage:[UIImage imageNamed:@"闪光开"] forState:UIControlStateNormal];
    } else{
        [_btnLamp setImage:[UIImage imageNamed:@"闪光关"] forState:UIControlStateNormal];
    }
    
}

-(void)onBtnBeautyClicked {
    [self hideBotMixAll];
    if (isTXfiter) {
        YBWeakSelf;
        [TXBaseBeautyView showBaseBeauty:^(NSString *eventStr, float value, NSString *filterName) {
            [weakSelf txBaseBeauty:eventStr value:value filter:filterName];
        }];
    }else{
        //[self.tiUIView createTiUIView:YES];
        self.mhShadowBtn.hidden = NO;
        [self.menusView showMenuView:YES];
    }
}
#pragma mark - 基础美颜开始
-(void)txBaseBeauty:(NSString *)eventStr value:(float)value filter:(NSString *)filterName {
    if ([eventStr isEqual:@"基础美颜-关闭"]) {
        [self onTiTapEvent];
    }
    if ([eventStr isEqual:@"基础美颜-美颜"]) {
        [[[TXUGCRecord shareInstance] getBeautyManager] setBeautyLevel:value];
    }
    if ([eventStr isEqual:@"基础美颜-美白"]) {
        [[[TXUGCRecord shareInstance] getBeautyManager] setWhitenessLevel:value];
    }
    if ([eventStr isEqual:@"基础美颜-滤镜"]) {
        if (![PublicObj checkNull:filterName]) {
            [[[TXUGCRecord shareInstance] getBeautyManager] setFilter:[UIImage imageWithContentsOfFile:filterName]];
        }else {
            [[[TXUGCRecord shareInstance] getBeautyManager ] setFilter:nil];//[UIImage new]
        }
    }
}
#pragma mark - 基础美颜结束
#pragma mark - TXVideoCustomProcessDelegate 自定义美颜 开始
- (GLuint)onPreProcessTexture:(GLuint)texture width:(CGFloat)width height:(CGFloat)height{
    if ([PublicObj isBaseBeauty]) {
        //普通美颜
        return texture;
    }
    GLuint newTexture = texture;
    /*
    if (_needScale){
        newTexture = [self.beautyManager processWithTexture:texture width:width height:height scale:0.75];
    }else{
        [self.beautyManager processWithTexture:texture width:width height:height];
    }
    */
    newTexture = [self.beautyManager getTextureProcessWithTexture:texture width:width height:height];
    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.menusView) {
            if (!isLoadWebSprout) {
                isLoadWebSprout = YES;
                [self.menusView setupDefaultBeautyAndFaceValue];
            }
        }
    });
    return newTexture;
}

-(void)onTiTapEvent {
    [self showBotMixAll];
}

//美狐
- (MHBeautyManager *)beautyManager {
    if (!_beautyManager) {
        _beautyManager = [[MHBeautyManager alloc] init];
    }
    return _beautyManager;
}
- (UIButton *)mhShadowBtn {
    if (!_mhShadowBtn) {
        _mhShadowBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _mhShadowBtn.frame = CGRectMake(0, 0, _window_width, _window_height);
        [_mhShadowBtn addTarget:self action:@selector(dismissMHUI) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_mhShadowBtn];
    }
    return _mhShadowBtn;
}
-(void)dismissMHUI {
    if (self.menusView.isShow) {
        //更新美颜值
        [sproutCommon updataMHValueToService];
        self.mhShadowBtn.hidden = YES;
        [self.menusView showMenuView:NO];
        [self onTiTapEvent];
    }else {
        [self.menusView showMenuView:YES];
    }
}
- (MHMeiyanMenusView *)menusView {
    if (!_menusView) {
        _menusView = [[MHMeiyanMenusView alloc] initWithFrame:CGRectMake(0, window_height - MHMeiyanMenuHeight - BottomIndicatorHeight, window_width, MHMeiyanMenuHeight) superView:self.view  beautyManager:self.beautyManager];
    }
    return _menusView;
}
- (void)beautyEffectWithLevel:(NSInteger)beauty whitenessLevel:(NSInteger)white ruddinessLevel:(NSInteger)ruddiness {
    [[[TXUGCRecord shareInstance] getBeautyManager] setBeautyStyle:0];
    [[[TXUGCRecord shareInstance] getBeautyManager] setBeautyLevel:beauty];
    [[[TXUGCRecord shareInstance] getBeautyManager] setWhitenessLevel:white];
    [[[TXUGCRecord shareInstance] getBeautyManager] setRuddyLevel:ruddiness];
    
}
#pragma mark - TXVideoCustomProcessDelegate 自定义美颜 结束
-(void)onBtnMusicClicked {
    WuyouTangMusicView *mVC = [[WuyouTangMusicView alloc]init];
    mVC.fromWhere = @"edit";
    mVC.pathEvent = ^(NSString *event, NSString *musicID) {
        if (_musicPath.length>0) {
            [self tcStopMuic];
        }
        _musicPath = event;
        _musicID = musicID;
        _haveBGM = YES;
    };
    YBNavigationController *nav = [[YBNavigationController alloc]initWithRootViewController:mVC];
    nav.modalPresentationStyle = 0;
    [self presentViewController:nav animated:YES completion:nil];
}
#pragma mark - 显示、隐藏按钮
-(void)hideBtnWhenRecord{
    _btnClose.hidden = YES;
    _btnLamp.hidden = YES;
    _btnCamera.hidden = YES;
    _btnBeauty.hidden = YES;
    _btnLocalVideo.hidden = YES;
    _btnPicSel.hidden = YES;
    _speedV.hidden = YES;
    _tPickView.hidden = YES;
    _musicBtn.hidden = YES;
    _btnDelete.hidden = YES;
    _btnDone.hidden = YES;
}
-(void)showBtnWhenEnd:(BOOL)isEnd{
    _btnClose.hidden = NO;
    _btnLamp.hidden = NO;
    _btnCamera.hidden = NO;
    _btnBeauty.hidden = NO;
//    if (!_videoRecording) {
//        _btnLocalVideo.hidden = NO;
//        _btnPicSel.hidden = NO;
//    }
    _speedV.hidden = (_recordType == RecordType_Chorus)?YES:NO;
    _tPickView.hidden = [[YBPower getVipSwitch] isEqual:@"0"] ? YES:NO;
    if ((_videoRecording && _currentRecordTime > 0) || _recordType == RecordType_Chorus) {
        _btnLocalVideo.hidden = YES;
        _btnPicSel.hidden = YES;
        _tPickView.hidden = YES;
    }
    
    _musicBtn.hidden = NO;
    if (_recordType == RecordType_Chorus || _isTakeSame) {
        _musicBtn.hidden = YES;
    }
    TXUGCPartsManager *partsManager = [TXUGCRecord shareInstance].partsManager;
    if ([partsManager getVideoPathList].count > 0) {
        _btnDelete.hidden = NO;
    }
    if (_currentRecordTime > MIN_RECORD_TIME) {
         _btnDone.hidden = NO;
    }
}
-(void)hideBotMixAll{
    //隐藏进度条、上传、美颜、录制、下一步
    _progressView.hidden = YES;
    _recordTimeLabel.hidden = YES;
    _btnLocalVideo.hidden = YES;
    _btnPicSel.hidden = YES;
    _btnStartRecord.hidden = YES;
    _btnDone.hidden = YES;
    _speedV.hidden = YES;
    _tPickView.hidden = YES;
    _btnDelete.hidden = YES;
}
-(void)showBotMixAll{
    _progressView.hidden = NO;
    _recordTimeLabel.hidden = NO;
    if (!_videoRecording) {
        _btnLocalVideo.hidden = NO;
        _btnPicSel.hidden = NO;
    }
    _btnStartRecord.hidden = NO;
    _speedV.hidden = NO;
    _tPickView.hidden = [[YBPower getVipSwitch] isEqual:@"0"] ? YES:NO;
    if (_recordType == RecordType_Chorus) {
        _btnLocalVideo.hidden = YES;
        _btnPicSel.hidden = YES;
        _speedV.hidden = YES;
        _tPickView.hidden = YES;
    }
    TXUGCPartsManager *partsManager = [TXUGCRecord shareInstance].partsManager;
    if ([partsManager getVideoPathList].count > 0) {
        _btnDelete.hidden = NO;
    }
    if (_currentRecordTime > MIN_RECORD_TIME) {
        _btnDone.hidden = NO;
    }
}

-(void)refreshRecordTime:(float)milliSecond {
    _currentRecordTime = milliSecond/1000.0;
    [_progressView update:_currentRecordTime / MAX_RECORD_TIME];
    NSInteger min = (int)_currentRecordTime / 60;
    NSInteger sec = (int)_currentRecordTime % 60;
    
    [_recordTimeLabel setText:[NSString stringWithFormat:@"%02ld:%02ld", min, sec]];
    [_recordTimeLabel sizeToFit];
    
    if (_currentRecordTime > MIN_RECORD_TIME) {
        _btnDone.hidden = NO;
        /*//rk_20200118 tx6.9解决合拍问题
        if (_recordType == RecordType_Chorus) {
            [YBProgressObj progressManeger].generationHidden = NO;
        }
         */
    }
    
    //录制过程中不可更改音乐
    if (_musicPath.length>0 && _currentRecordTime>0) {
        _musicBtn.alpha = 0.5;
        _musicBtn.enabled = NO;
    }else{
        _musicBtn.alpha = 1;
        _musicBtn.enabled = YES;
    }
    if (_recordType == RecordType_Chorus || _isTakeSame) {
        _musicBtn.hidden = YES;
    }
    
    if (_isBackDelete && _recordType == RecordType_Chorus) {
        [_editor previewAtTime:_currentRecordTime];
        _isBackDelete = NO;
    }
    
}
#pragma mark ---- VideoRecordListener ----
-(void) onRecordEvent:(NSDictionary *)evt{
    NSLog(@"event:%@",evt);
}
-(void) onRecordProgress:(NSInteger)milliSecond {
    NSLog(@"=====<><><>==%ld",(long)milliSecond);
    
    [self refreshRecordTime:(float)milliSecond];
}

-(void) onRecordComplete:(TXUGCRecordResult*)result {
    
    if (_appForeground)    {
        if (result.retCode == UGC_RECORD_RESULT_OK ||result.retCode ==UGC_RECORD_RESULT_OK_UNREACH_MINDURATION) {
            NSLog(@"录完了录完了录完了录完了录完了录完了录完了录完了录完了录完了录完了");
            if (_recordType == RecordType_Chorus) {
                [self sameRecordComplete:result];
            }else {
                [self pushresult:result isAlbum:NO];
            }
            [self refreshRecordTime:0.0];
            [self stopCameraPreview:YES];
        }
        else if(result.retCode == UGC_RECORD_RESULT_OK_BEYOND_MAXDURATION){
            
            if (_recordType == RecordType_Chorus) {
                [self sameRecordComplete:result];
            }else {
                [self pushresult:result isAlbum:NO];
            }
            [self refreshRecordTime:0.0];
            [self stopCameraPreview:YES];
                           [self stopVideoRecord];
            
        }
        else if(result.retCode == UGC_RECORD_RESULT_OK_INTERRUPT){
            [MBProgressHUD showPop:YZMsg(@"录制被打断")];
        }
//        else if(result.retCode == UGC_RECORD_RESULT_OK_UNREACH_MINDURATION){
//            [MBProgressHUD showPop:[NSString stringWithFormat:@"%@%f%@",YZMsg(@"至少要录够"),MIN_RECORD_TIME,YZMsg(@"秒")]];
//        }
        else if(result.retCode == UGC_RECORD_RESULT_FAILED){
            [MBProgressHUD showPop:YZMsg(@"视频录制失败")];
        }
    }
    //分片不再使用的时候请主动删除，否则分片会一直存在本地，导致内存占用越来越大，下次startRecord时候，SDK也会默认加载当前分片
    [[TXUGCRecord shareInstance].partsManager deleteAllParts];
    if (_musicPath.length>0) {
//        [[TXUGCRecord shareInstance] setBGM:nil];
    }
}
-(void)pushresult:(TXUGCRecordResult *)recordResult isAlbum:(BOOL)isAlbum{
    
    TCVideoEditViewController *vc = [[TCVideoEditViewController alloc] init];
    vc.isAlbum = isAlbum;
    [vc setVideoPath:recordResult.videoPath];
    vc.musicPath = _musicPath;
    vc.musicID = _musicID;
    vc.haveBGM = _haveBGM;
    vc.isTakeSame = _isTakeSame;
    vc.recordType = _recordType;
    [self.navigationController pushViewController:vc animated:YES];
    
//    [self releaseEditor];
    [self destroyRecordSource];
}
#pragma mark - 播放音乐 start
-(void)tcPlayMusic{
    if (_musicPlayed==NO) {
       float length = [[TXUGCRecord shareInstance] setBGM:_musicPath];
        NSLog(@"======%f",length);
        if (length>0) {
            [[TXUGCRecord shareInstance]playBGMFromTime:0 toTime:length withBeginNotify:^(NSInteger errCode) {
                //beginNotify: 音乐播放开始的回调通知
                NSLog(@"开始播音乐");
            } withProgressNotify:^(NSInteger progressMS, NSInteger durationMS) {
                //beginNotify: 音乐播放开始的回调通知
                NSLog(@"音乐进度%ld/%ld",(long)progressMS,(long)durationMS);
            } andCompleteNotify:^(NSInteger errCode) {
                //completeNotify: 音乐播放结束的回调通知
                NSLog(@"播放完毕%ld",errCode);
            }];
        }
        [[TXUGCRecord shareInstance] setBGMLoop:YES];
        CGFloat bgVolume = ([PublicObj getSysOutputVolume] < 0.2 )? 0.3 : [PublicObj getSysOutputVolume];
        [[TXUGCRecord shareInstance] setBGMVolume:bgVolume];
        //播放背景音乐的时候禁止麦克风采集声音
        [[TXUGCRecord shareInstance] setMicVolume:0];
    }else{
        [[TXUGCRecord shareInstance] resumeBGM];
    }
}
-(void)tcPause{
    _musicPlayed = YES;
    [[TXUGCRecord shareInstance] pauseBGM];
}
-(void)tcStopMuic{
    _musicPlayed = NO;
    [[TXUGCRecord shareInstance] stopBGM];
}
#pragma mark - 播放音乐 end

#pragma mark - 通知
-(void)onAudioSessionEvent:(NSNotification*)notification {
    NSDictionary *info = notification.userInfo;
    AVAudioSessionInterruptionType type = [info[AVAudioSessionInterruptionTypeKey] unsignedIntegerValue];
    if (type == AVAudioSessionInterruptionTypeBegan) {
        // 在10.3及以上的系统上，分享跳其它app后再回来会收到AVAudioSessionInterruptionWasSuspendedKey的通知，不处理这个事件。
        if ([info objectForKey:@"AVAudioSessionInterruptionWasSuspendedKey"]) {
            return;
        }
        _appForeground = NO;
        if (!_isPaused && _videoRecording)
            [self onBtnRecordStartClicked];
    }else{
        AVAudioSessionInterruptionOptions options = [info[AVAudioSessionInterruptionOptionKey] unsignedIntegerValue];
        if (options == AVAudioSessionInterruptionOptionShouldResume) {
            _appForeground = YES;
        }
    }
}
- (void)onAppDidEnterBackGround:(UIApplication*)app {
    _appForeground = NO;
    if (!_isPaused && _videoRecording)
        [self onBtnRecordStartClicked];
}

- (void)onAppWillEnterForeground:(UIApplication*)app {
    _appForeground = YES;
}

#pragma mark - 合拍开始
-(void)sameRecordComplete:(TXUGCRecordResult*)result {
    [YBProgressObj progressManeger].generationHidden = NO;
    //获取录制视频的宽高
    TXVideoInfo *videoInfo = [TXVideoInfoReader getVideoInfo:result.videoPath];
    CGFloat width = videoInfo.width;
    CGFloat height = videoInfo.height;

    [_joiner setVideoPathList:@[result.videoPath, _mp4Path]];
    
    //录制视频和原视频左右排列
    CGRect recordScreen = CGRectMake(0, 0, width, height);
    CGRect playScreen = CGRectMake(width, 0, width, height);
    [_joiner setSplitScreenList:@[[NSValue valueWithCGRect:recordScreen],[NSValue valueWithCGRect:playScreen]] canvasWidth:width * 2 canvasHeight:height];
    [_joiner splitJoinVideo:VIDEO_COMPRESSED_540P videoOutputPath:_resultPath];
}

-(void) onJoinProgress:(float)progress {
    NSLog(@"--====:%f",progress);
    [YBProgressObj progressManeger].generationProgress = progress;
}

-(void) onJoinComplete:(TXJoinerResult *)result {
    [YBProgressObj progressManeger].generationHidden = YES;
    [[YBProgressObj progressManeger] progressDestroy];
    
    TXUGCRecordResult *recordResult = [TXUGCRecordResult new];
    recordResult.videoPath  = _resultPath;
    [self pushresult:recordResult isAlbum:YES];
    
    [self removeSameEventOfFile];
}
-(void)removeSameEventOfFile {
    if (_recordType == RecordType_Chorus && ![PublicObj checkNull:_mp4Path]) {
        BOOL isOk = [[NSFileManager defaultManager] removeItemAtPath:_mp4Path error:nil];
        NSLog(@"===:%d",isOk);
    }
}
#pragma mark - 合拍结束
- (BOOL)prefersStatusBarHidden {
    return _barHidden;
}
#pragma mark - 图片转场 开始
-(void)onBtnPicSelClicked {
    _barHidden = NO;
    [UIApplication sharedApplication].statusBarHidden = NO;
    [self selLocOrPicTransition];
    
    TZImagePickerController *imagePC = [[TZImagePickerController alloc]initWithMaxImagesCount:1 delegate:self];
    imagePC.preferredLanguage = [lagType isEqual:ZH_CN] ? @"zh-Hans":@"en";
    imagePC.iconThemeColor = Pink_Cor;
    imagePC.naviBgColor = CellRow_Cor;
    imagePC.oKButtonTitleColorNormal = Pink_Cor;
    imagePC.oKButtonTitleColorDisabled = Pink_Cor_Dis;
    imagePC.allowTakePicture = NO;
    imagePC.allowTakeVideo = NO;
    imagePC.allowPickingVideo = NO;
    imagePC.showSelectedIndex = YES;
    imagePC.allowCrop = NO;
    imagePC.allowPickingOriginalPhoto = NO;
    imagePC.minImagesCount = 3;
    imagePC.maxImagesCount = 10;
    imagePC.modalPresentationStyle = 0;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self presentViewController:imagePC animated:YES completion:nil];
    });
}
- (void)tz_imagePickerControllerDidCancel:(TZImagePickerController *)picker{
    [UIApplication sharedApplication].statusBarHidden = YES;
     _barHidden = YES;
}
//picker delegate
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto{
    
    NSMutableArray *imgArray = [NSMutableArray array];
    for (UIImage *img in photos) {
        UIImage *scaleImg = [PublicObj scaleImage:img scaleToSize:[PublicObj getObjSize:img.size]];
        [imgArray addObject:scaleImg];
    }
    _barHidden = YES;
    [UIApplication sharedApplication].statusBarHidden = NO;
    //跳转
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        YBPicTransitionVC *picVC = [[YBPicTransitionVC alloc]init];
        picVC.imageList = [imgArray copy];
        picVC.musicID = _musicID;
        picVC.musicPath = _musicPath;
        picVC.haveBGM = _haveBGM;
        picVC.isTakeSame = _isTakeSame;
        [[YBBaseAppDelegate sharedAppDelegate]pushViewController:picVC animated:YES];
        [self stopCameraPreview:YES];
    });
    
}
#pragma mark - 图片转场 结束

#pragma mark - 选取本地视频 TZ
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingVideo:(UIImage *)coverImage sourceAssets:(PHAsset *)asset {
    [MBProgressHUD showMessage:@""];
    PHVideoRequestOptions* options = [[PHVideoRequestOptions alloc] init];
    options.version = PHVideoRequestOptionsVersionOriginal;
    options.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic;
    options.networkAccessAllowed = YES;
    YBWeakSelf;
    [[PHImageManager defaultManager] requestAVAssetForVideo:asset options:options resultHandler:^(AVAsset* avasset, AVAudioMix* audioMix, NSDictionary* info){
        NSString * sandboxExtensionTokenKey = info[@"PHImageFileSandboxExtensionTokenKey"];
        NSArray * arr = [sandboxExtensionTokenKey componentsSeparatedByString:@";"];
        NSString * filePath = arr[arr.count - 1];
        if (!filePath){
            AVURLAsset *videoAsset = (AVURLAsset*)avasset;
            filePath =[videoAsset.URL absoluteString];
            
            NSURLComponents *urlComponents = [NSURLComponents componentsWithURL:videoAsset.URL resolvingAgainstBaseURL:NO];
            urlComponents.fragment = nil;
            filePath = [urlComponents.URL absoluteString];
        }
        CMTime   time = [avasset duration];
        int seconds = ceil(time.value/time.timescale);
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUD];
            if (seconds < normal_min) {
                [MBProgressHUD showPop:YZMsg(@"视频时长过短,请重新选择")];
                return ;
            }
            if (seconds>normal_max && [[YBPower getCanTakeLongVideo] isEqual:@"0"] && [[YBPower getVipSwitch] isEqual:@"1"]) {
                [self vipLimiteAlert:[NSString stringWithFormat:@"%@%.f%@",YZMsg(@"您不是会员用户,无选取超过"),normal_max,YZMsg(@"秒长视频")]];
                return;
            }
            if (filePath) {
                [weakSelf zhuanma:filePath];
            }else {
                [MBProgressHUD showPop:YZMsg(@"选取失败")];
            }
        });
    }];
    
}
#pragma mark - 自定义相册选取视频 开始
-(void)zhuanma:(NSString *)videlPathsss{
    videobackImage = [PublicObj getVideoPreViewImageWithPath:[NSURL URLWithString:videlPathsss]];
    if ([videlPathsss hasSuffix:@".mp4"]||[videlPathsss hasSuffix:@".MP4"]||[videlPathsss hasSuffix:@".Mp4"]||[videlPathsss hasSuffix:@".mP4"]) {
        TXUGCRecordResult *recordResult = [TXUGCRecordResult new];
        recordResult.coverImage = videobackImage;
        recordResult.videoPath  = videlPathsss;
        [self pushresult:recordResult isAlbum:YES];
        [self stopCameraPreview:YES];
    }else{
        [MBProgressHUD showMessage:YZMsg(@"视频转码中")];
        NSString *random = [PublicObj getNameBaseCurrentTime:@""];
        AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:videlPathsss] options:nil];
        AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]initWithAsset:avAsset presetName:AVAssetExportPreset1280x720];
        exportPath = [NSString stringWithFormat:@"%@/Library/Caches/movie_%@.mp4",NSHomeDirectory(),random];
        NSLog(@"exportPath=%@",exportPath);
        exportSession.outputURL = [NSURL fileURLWithPath:exportPath];
        exportSession.outputFileType = AVFileTypeMPEG4;
        //exportSession.canPerformMultiplePassesOverSourceMediaData = YES;
        [exportSession exportAsynchronouslyWithCompletionHandler:^{
            int exportStatus = (int)exportSession.status;
            switch (exportStatus) {
                case AVAssetExportSessionStatusFailed:
                    NSLog(@"Export failed: %@", [[exportSession error] localizedDescription]);
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [MBProgressHUD hideHUD];
                        [MBProgressHUD showError:YZMsg(@"转码失败,请更换视频")];
                    });
                    break;
                case AVAssetExportSessionStatusCancelled:
                    NSLog(@"Export canceled");
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [MBProgressHUD hideHUD];
                        [MBProgressHUD showError:YZMsg(@"转码失败,请更换视频")];
                    });
                    break;
                case AVAssetExportSessionStatusCompleted:
                    NSLog(@"转换成功");
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [MBProgressHUD hideHUD];
                        TXUGCRecordResult *recordResult = [TXUGCRecordResult new];
                        recordResult.coverImage = videobackImage;
                        recordResult.videoPath  = exportPath;
                        [self pushresult:recordResult isAlbum:YES];
                        [self stopCameraPreview:YES];
                    });
                    break;
            }
        }];
    }
    
}
#pragma mark - 自定义相册选取视频 结束


@end


/* 方式三导出:这个mp4格式只能到处低质量的*/
/*
[MBProgressHUD showMessage:@"请稍后..."];
[[TZImageManager manager] getVideoOutputPathWithAsset:asset presetName:AVAssetExportPresetLowQuality success:^(NSString *outputPath) {
    dispatch_async(dispatch_get_main_queue(), ^{
        [MBProgressHUD hideHUD];
        NSLog(@"视频导出到本地完成,沙盒路径为:%@",outputPath);
        if (outputPath) {
           TXUGCRecordResult *recordResult = [TXUGCRecordResult new];
            recordResult.coverImage = coverImage;//videobackImage;
           recordResult.videoPath  = outputPath;
           [self pushresult:recordResult isAlbum:YES];
        }else{
           [MBProgressHUD showPop:@"请重新选择(iCloud视频请先在本地相册下载后上传)"];
        }
    });
} failure:^(NSString *errorMessage, NSError *error) {
    dispatch_async(dispatch_get_main_queue(), ^{
        [MBProgressHUD hideHUD];
        [MBProgressHUD showPop:errorMessage];
    });
    NSLog(@"视频导出失败:%@,error:%@",errorMessage, error);
}];
 */

/* 方式一 系统选择
UIImagePickerController *imagePickerController = [UIImagePickerController new];
imagePickerController.delegate = self;
imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
imagePickerController.mediaTypes = [[NSArray alloc] initWithObjects: (NSString *) kUTTypeMovie, nil];
imagePickerController.videoQuality = UIImagePickerControllerQualityTypeHigh;
[self presentViewController:imagePickerController animated:YES completion:nil];

return;
 */

/* 方式二 自定义相册选择视频
__weak TCVideoRecordViewController *weakSelf = self;
AlbumVideoVC *albunVC = [[AlbumVideoVC alloc]init];
albunVC.selEvent = ^(NSString *path) {
    [weakSelf zhuanma:path];
};
[self presentViewController:albunVC animated:YES completion:nil];
*/
/**
 #pragma mark - 系统相册 (测试) start
 - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
     [picker dismissViewControllerAnimated:YES completion:nil];
 }
 -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
     [picker dismissViewControllerAnimated:YES completion:nil];
     NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
     if ([type isEqualToString:@"public.movie"]) {
         //先把图片转成NSData
         NSString *url = [[info objectForKey:UIImagePickerControllerMediaURL] path];
         if (url) {
             [self zhuanma:url];
         }
     }
 }
 - (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
     if ([UIDevice currentDevice].systemVersion.floatValue < 11) {
         return;
     }
     if ([viewController isKindOfClass:NSClassFromString(@"PUPhotoPickerHostViewController")]) {
         [viewController.view.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
             if (obj.frame.size.width < 42) {
                 [viewController.view sendSubviewToBack:obj];
                 *stop = YES;
             }
         }];
     }
 }
 -(void)selectedPhoto:(NSDictionary *)subdic{
     NSString *videoS = [NSString stringWithFormat:@"%@",[subdic valueForKey:@"videoURL"]];
     [self zhuanma:videoS];
 }
 #pragma mark - 系统相册 (测试) end
 */
